<template>
  <a-modal
    :visible="open"
    title="资产调拨"
    width="90%"
    @ok="handleTransferSubmit"
    @cancel="onClose"
  >
    <div>
      <div style="display: flex;justify-content: space-between">
        <a-space>
          客户
          <a-select
            ref="select"
            v-model:value="assetSo.clientId"
            style="width: 120px;"
            @change="handleChangeClient"
            allowClear
          >
            <a-select-option
              v-for="item in clientList"
              :key="item.id"
              :value="item.id"
            >{{ item.clientName }}
            </a-select-option
            >
          </a-select>
          楼层
          <a-select
            ref="select"
            v-model:value="assetSo.floorId"
            style="width: 120px;"
            @change="handleChangeFloor"
            allowClear
          >
            <a-select-option
              v-for="item in floorList"
              :key="item.id"
              :value="item.id"
            >{{ item.floor }}
            </a-select-option
            >
          </a-select>
          房间
          <a-select
            ref="select"
            v-model:value="assetSo.positionId"
            style="width: 120px;"
            allowClear
          >
            <a-select-option
              v-for="item in roomList"
              :key="item.id"
              :value="item.id"
            >{{ item.position }}
            </a-select-option
            >
          </a-select>
          <a-button @click="handleList" type="primary">查询</a-button>
        </a-space>
        <a-space>

          调拨至楼层
          <a-select
            ref="select"
            v-model:value="transferBo.floorId"
            style="width: 120px;"
            @change="handleChangeTransferFloor"
            allowClear
          >
            <a-select-option
              v-for="item in floorList"
              :key="item.id"
              :value="item.id"
            >{{ item.floor }}
            </a-select-option
            >
          </a-select>
          房间
          <a-select
            ref="select"
            v-model:value="transferBo.positionId"
            style="width: 120px;"
            allowClear
          >
            <a-select-option
              v-for="item in transferRoomList"
              :key="item.id"
              :value="item.id"
            >{{ item.position }}
            </a-select-option
            >
          </a-select>
          <a-input v-model:value="transferBo.address" placeholder="资产地址" style="width:160px;">

          </a-input>
          <a-input v-model:value="transferBo.reason" placeholder="调拨原因"
                   style="width:160px;"></a-input>
        </a-space>
      </div>
      <a-transfer
        style="margin-top:8px"
        v-model:target-keys="targetKeys"
        :data-source="dataSource"
        :show-search="true"
        :filter-option="(inputValue, item) => item.assetCode.indexOf(inputValue) !== -1"
        :show-select-all="true"
        @change="onChange"
        :rowKey="record => record.id"

      >
        <template
          #children="{
          direction,
          filteredItems,
          selectedKeys,
          disabled,
          onItemSelectAll,
          onItemSelect,
        }"
        >
          <a-table
            :row-selection="
            getRowSelection({
            disabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
            :columns="columns"
            :data-source="filteredItems"
            size="small"
            :custom-row="
            ({ id }) => ({
              onClick: () => {
                onItemSelect(id, !selectedKeys.includes(id));
              },
            })
          "
            :rowKey="record => record.id"
            :loading="loading"
          />
        </template>
      </a-transfer>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import {
  computed,
  defineProps,
  onMounted,
  ref,
  unref,
  defineEmits,
  reactive,
  type PropType
} from "vue";
import {
  type AssetBo,
  type AssetPageVo, type AssetSo,
  type ClientVo,
  type FloorVo,
  listClientApi, listFloorApi, listPositionApi,
  pageAssetApi, type PositionVo, submitTransferApi
} from "#/api";
import {message} from "ant-design-vue";
import {SearchOutlined} from "@ant-design/icons-vue";

const props = defineProps({
  open: {
    type: Boolean,
    required: true,
    default: false,
  },

});
const emit = defineEmits(['close'])

const assetSo = reactive<AssetSo>({
  keyword: '',
  clientId: '',
  floorId: '',
  positionId: ''
})

const transferBo = reactive({
  floorId: '',
  positionId: '',
  address: '',
  reason: '',
  assets: []
})

const clientList = ref<ClientVo[]>([]);
const floorList = ref<FloorVo[]>([]);
const roomList = ref<PositionVo[]>([]);
const transferRoomList = ref<PositionVo[]>([]);
const loading = ref<boolean>(false);
const columns = [
  {
    title: '资产编码',
    dataIndex: 'assetCode',
    key: 'assetCode',
    width: 160,
    align: 'center',
  },
  {
    title: '资产名称',
    dataIndex: 'assetName',
    key: 'contractName',
    align: 'center',
  },
  {
    title: '所属客户',
    dataIndex: 'clientName',
    key: 'clientName',
    width: 160,
    align: 'center',
  },
  {
    title: '资产位置',
    dataIndex: 'address',
    key: 'address',
    width: 160,
    align: 'center',
  },
];
const dataSource = ref<AssetPageVo[]>([]);

const targetKeys = ref<string[]>([]);
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 99999,
  size: '',
  showSizeChanger: false,
  showQuickJumper: false,
});
const pageParam = computed(() => ({
  query: unref<AssetSo>(assetSo),
  current: pagination.value?.current,
  size: pagination.value?.pageSize,
}));

const onChange = (nextTargetKeys: string[], direction, moveKeys) => {
  console.log('nextTargetKeys', nextTargetKeys, direction, moveKeys);
};
const onClose = () => {
  console.log('close')
  emit('close')
}

const getRowSelection = ({
                           disabled,
                           selectedKeys,
                           onItemSelectAll,
                           onItemSelect,
                         }: Record<string, any>) => {
  return {
    onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
      const treeSelectedKeys = selectedRows.map(({id}) => id);
      onItemSelectAll(treeSelectedKeys, selected);
    },
    onSelect({id}: Record<string, string>, selected: boolean) {
      console.log('onSelect', selected)
      onItemSelect(id, selected);
    },
    selectedRowKeys: selectedKeys,
  };
};

onMounted(() => {
  console.log('onMounted')
  list();
  listClient();
});
const list = async () => {
  loading.value = true;
  const res = await pageAssetApi(unref(pageParam)).finally(() => loading.value = false);
  console.log('res.records', res.records)
  dataSource.value = res.records;
  pagination.value.total = Number(res.total);
  pagination.value.current = Number(res.current);
}

const listClient = async () => {
  const res = await listClientApi();
  clientList.value = res;
}

const handleChangeClient = async () => {
  const res = await listFloorApi({clientId: assetSo.clientId});
  floorList.value = res;
  assetSo.floorId = ''
  assetSo.positionId = ''
}
const handleChangeFloor = async () => {
  if (assetSo.floorId == null) {
    roomList.value = []
    assetSo.positionId = ''
    return
  }
  const res = await listPositionApi({floorId: assetSo.floorId});
  roomList.value = res;
  assetSo.positionId = ''
}
const handleChangeTransferFloor = async () => {
  if (transferBo.floorId == null) {
    transferRoomList.value = []
    transferBo.positionId = ''
    return
  }
  const res = await listPositionApi({floorId: transferBo.floorId});
  transferRoomList.value = res;
  transferBo.positionId = ''
}

const pageChange = (page) => {
  pagination.value.current = page.current
  list()
}
const handleList = () =>{
  targetKeys.value = []
  list();
}
const handleTransferSubmit = async () => {
  console.log('targetKeys', targetKeys.value)
  transferBo.assets.push(...targetKeys.value)
  console.log('transferBo', transferBo)
  const res = await submitTransferApi(transferBo)
  message.success("调拨成功")
  emit('close')
}
</script>
